﻿using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.IdentityModel.Tokens;
using TokenApi.Contract;
using TokenApi.Contract.Domain;
using TokenApi.Service.Contract;
using TokenApi.Service.Infrastructure;

namespace TokenApi.Service.Service;

public sealed class AliyunFCService(IHttpClientFactory httpClientFactory) : IChatService
{
    public const string Name = "AliyunFC";

    public async IAsyncEnumerable<CompletionResult> CompletionsAsync<T>(ChatCompletionDto<T>? dto,
        ChatChannel data = null)
    {
        var httpClient = httpClientFactory.CreateClient(Name);

        if (dto.messages is not List<ChatCompletionRequestMessage>)
        {
            throw new NotSupportedException();
        }

        if (dto.messages is List<ChatCompletionRequestMessage> chats)
        {
            var input = new AliyunFCResult()
            {
                input = new AliyunFCInput()
                {
                    messages = chats.Select(x => new AliyunFCMessages()
                    {
                        content = x.content,
                        role = x.role
                    }).ToArray()
                },
                parameters = new AliyunFCParameters()
                {
                    max_length = dto.max_tokens,
                    do_sample = true,
                }
            };

            var response = await httpClient?.HttpRequestRaw(data.Address, input, data.Key);


            var reader = new StreamReader(await response.Content.ReadAsStreamAsync());

            while (await reader.ReadLineAsync() is { } line)
            {
                var res = JsonSerializer.Deserialize<AliyunFCOutput>(line, new JsonSerializerOptions()
                {
                    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
                });
                var content = res?.Data.message.content;

                if (content.IsNullOrEmpty()) continue;

                yield return new CompletionResult(content);
            }
        }
    }

    public class AliyunFCResult
    {
        public AliyunFCInput input { get; set; }
        public AliyunFCParameters parameters { get; set; }
    }

    public class AliyunFCInput
    {
        public AliyunFCMessages[] messages { get; set; }
    }

    public class AliyunFCMessages
    {
        public string content { get; set; }
        public string role { get; set; }
    }

    public class AliyunFCParameters
    {
        public bool do_sample { get; set; }
        public int max_length { get; set; }
    }


    public class AliyunFCOutput
    {
        public int Code { get; set; }
        public Data Data { get; set; }
        public string Message { get; set; }
        public string RequestId { get; set; }
        public bool Success { get; set; }
    }

    public class Data
    {
        public AliyunFCMessages message { get; set; }
    }
}